import {sm4 as SM4} from "gm-crypt"

const secretKey = 'D4F7el9oSl8lI#iU'
const iv = 'vkto3Q}U[{ga7myx'
const sm4 = new SM4({key: decryptKey(secretKey), iv, mode: "cbc"})

/**
 * SM4 encode
 * @param content
 * @returns {String}
 */
export function encodeSM4(content) {
    return sm4.encrypt(content)
}

/**
 * SM4 decode
 * @param content
 * @returns {String}
 */
export function decodeSM4(content) {
    return sm4.decrypt(content)
}

function decryptKey(key) {
    let data = Array.from(key)
    let j = data.length
    for (let i = 0; i < Math.floor(j / 2); i += 2) {
        if (i + 1 <= Math.floor(j / 2) - 1) {
            let t
            if (i % 4 === 0) {
                t = data[i]
                data[i] = data[i + Math.floor(j / 2) + 1]
                data[i + Math.floor(j / 2) + 1] = t
            } else {
                t = data[i + 1]
                data[i + 1] = data[i + Math.floor(j / 2)]
                data[i + Math.floor(j / 2)] = t
            }
        }
    }
    return data.join('')
}
